<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/6/25 10:10
 * Modified Time: 2019/6/25 10:10
 * Version: 2.0
 */

namespace App\Modules\Store\Services;

use App\Exceptions\AllValidatorException;
use App\Exceptions\DbException;
use App\Exceptions\NotFoundException;
use App\Lib\Facades\FLAuth;
use App\Lib\Utilities;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\Inventory\Repositories\GoodsOrderRepository;
use App\Modules\Live\Repositories\LiveRepository;
use App\Modules\Live\Services\LiveService;
use App\Modules\MemberCard\Repositores\MemberCardFlowRepository;
use App\Modules\MemberCard\Repositores\MemberCardRepository;
use App\Modules\Order\Repositories\OrderRepository;
use App\Modules\Order\Repositories\RoyaltyRepository;
use App\Modules\Partner\Repositories\UserAccountRepository;
use App\Modules\Partner\Repositories\UserInviteRepository;
use App\Modules\Service\Repositories\ServiceRepository;
use App\Modules\Store\Criterias\GetMyLikeStoreCriteria;
use App\Modules\Store\Criterias\GetStoreInfoCriteria;
use App\Modules\Store\Criterias\GetStoreInfoAppCriteria;
use App\Modules\Store\Criterias\GetStoreListCriteria;
use App\Modules\Store\Criterias\GetStorePaymentCodeCriteria;
use App\Modules\Store\Criterias\GetStorePhotoCriteria;
use App\Modules\Store\Criterias\GetStorePictureCriteria;
use App\Modules\Store\Criterias\GetStoreResourceCriteria;
use App\Modules\Store\Criterias\GetStoreViedoCriteria;
use App\Modules\Store\Repositories\StoreLikeRepository;
use App\Modules\Store\Repositories\StorePaymentRoyaltyRepository;
use App\Modules\Store\Repositories\StorePhotoRepository;
use App\Modules\Store\Repositories\StoreRankRepository;
use App\Modules\Store\Repositories\StoreRepository;
use App\Modules\System\Repositories\PictureRepository;
use App\Modules\System\Repositories\RoleRepository;
use App\Modules\System\Repositories\UserStoreRepository;
use App\Modules\System\Repositories\StoreResourceRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;
use mysql_xdevapi\Exception;

class StoreService extends BaseService
{
    private $userAccountRepository;
    private $storeRepository;
    private $storeResourceRepository;
    private $userStoreRepository;
    private $storeRankRepository;
    private $storeLikeRepository;
    private $employeeRepository;
    private $storePaymentRoyaltyRepository;
    private $storePhotoRepository;
    private $userInviteRepository;
    private $orderRepository;
    private $memberCardFlowRepository;
    private $goodsOrderRepository;
    private $serviceRepository;
    private $royaltyRepository;
    private $pictureRepository;
	private  $liveRepository;
    public function __construct(StoreRepository $storeRepository,
                                UserAccountRepository $userAccountRepository,
                                StoreResourceRepository $storeResourceRepository,
                                UserStoreRepository $userStoreRepository,
                                EmployeeRepository $employeeRepository,
                                StoreRankRepository $storeRankRepository,
                                StorePaymentRoyaltyRepository $storePaymentRoyaltyRepository,
                                UserInviteRepository $userInviteRepository,
                                StorePhotoRepository $storePhotoRepository,
                                StoreLikeRepository $storeLikeRepository,
                                ServiceRepository $serviceRepository,
                                OrderRepository $orderRepository,
                                MemberCardFlowRepository $memberCardFlowRepository,
                                GoodsOrderRepository $goodsOrderRepository,
                                RoyaltyRepository $royaltyRepository,
                                PictureRepository $pictureRepository,LiveRepository $liveRepository)
    {
        $this->storeRepository = $storeRepository;
        $this->userAccountRepository = $userAccountRepository;
        $this->storeResourceRepository = $storeResourceRepository;
        $this->userStoreRepository = $userStoreRepository;
        $this->storeRankRepository = $storeRankRepository;
        $this->employeeRepository = $employeeRepository;
        $this->userInviteRepository = $userInviteRepository;
        $this->storePaymentRoyaltyRepository = $storePaymentRoyaltyRepository;
        $this->storePhotoRepository = $storePhotoRepository;
        $this->storeLikeRepository = $storeLikeRepository;
        $this->orderRepository = $orderRepository;
        $this->memberCardFlowRepository = $memberCardFlowRepository;
        $this->goodsOrderRepository = $goodsOrderRepository;
        $this->serviceRepository = $serviceRepository;
        $this->royaltyRepository = $royaltyRepository;
        $this->pictureRepository = $pictureRepository;
        $this->liveRepository = $liveRepository;
    }

    /**
     * 新建店铺
     * @param $name
     * @param $phone
     * @param $wechat
     * @param $profile
     * @param $longitude
     * @param $latitude
     * @param $invite_code
     * @param $adcode
     * @param $uid
     * @param $address
     * @return mixed
     * @throws AllValidatorException
     * @throws NotFoundException
     * @throws ValidatorException
     */
    public function createStore($name,
                                $phone,
                                $wechat,
                                $profile,
                                $longitude,
                                $latitude,
                                $invite_code,
                                $adcode,
                                $uid,
                                $address)
    {

        $user_id = FLAuth::id();
        // 验证邀请码是否存在
        if (!empty($invite_code)) {
            $inviteInfo = $this->employeeRepository->InviteCodeIsExisted($invite_code);
        }
        //查找同地区有无重名店铺
        if ($this->storeRepository->checkCityDoubleNameStore($name, $adcode)) {
            throw new AllValidatorException(['msg' => '该地区已有同名店铺']);
        }

        DB::beginTransaction();
        try {
            //创建店铺
            $new_store = $this
                ->storeRepository
                ->createStore(
                    $user_id,
                    $name,
                    $phone,
                    $wechat,
                    $profile,
                    $longitude,
                    $latitude,
                    $invite_code,
                    $adcode,
                    $uid,
                    $address
                );
            $new_store_id = $new_store->id;

            //判断有无常驻店铺
            if ($this->userStoreRepository->getUserPermanentStore($user_id)) {
                $is_defult = 0;
            } else {
                $is_defult = 1;
            }

            //建立店长关联
            $this->userStoreRepository->createUserStore($new_store_id, $user_id, 1, $is_defult);

            //建立理发师关联
            $this->userStoreRepository->createUserStore($new_store_id, $user_id, 2, $is_defult);


            //初始化店铺提成
            $this->storePaymentRoyaltyRepository->newstoreCreatePaymentRoyalty($new_store_id);

            //填了邀请码
            if ($invite_code) {
                $this->createCityPartner($user_id, $adcode, $invite_code);
            }


            DB::commit();
            return $new_store;
        } catch (Exception $e) {
            DB::rollBack();
            throw new ValidatorException(new MessageBag([$e->getMessage()]));
        }


    }

    /**
     * @param $user_id
     * @param $adcode
     * @param $invite_code
     * @return bool
     */
    private function createCityPartner($user_id, $adcode, $invite_code)
    {
        //查询是否已经是合伙人了
        if (!$this->userAccountRepository->getUserAccountByUserId($user_id)->city) {
            //判断是不是邀请的自己
            //根据邀请码获取用户
            $invite_user = $this->employeeRepository->getUserByInviteCode($invite_code);
            if ($invite_user) {
                if ($invite_user->id != $user_id) {
                    //查询入驻顺序
                    $ranking = $this->userAccountRepository->getUserAccountListByAdcode($adcode)->count() + 1;
                    if ($ranking <= 30) {
                        $share = 3;
                    } elseif ($ranking > 30 && $ranking <= 100) {
                        $share = 2;
                    } elseif ($ranking > 100 && $ranking <= 300) {
                        $share = 1;
                    } elseif ($ranking > 300 && $ranking <= 1000) {
                        $share = 0.5;
                    } else {
                        $share = 0.1;
                    }

                    //建立城市合伙人
                    $this->userAccountRepository->createPartner($user_id, $adcode, $ranking, $share);

                    //若填写邀请码 给邀请人奖励
                    if ($invite_code) {
                        $invite_user_id = $invite_user->id;

                        //创建邀请记录

                        $this->userInviteRepository->createUserInvite($invite_user_id, $user_id);

                        //邀请账户加钱
                        $this->userAccountRepository->addMoneyByUserId($invite_user_id, 180);
                    }
                }
            }
        }

        return true;
    }

    /**
     * @param $store_id
     * @return mixed
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getStoreInfoApp($store_id)
    {
        return $this->storeRepository->pushCriteria(new getStoreInfoAppCriteria($store_id))->first();
    }

    /**
     * 根据店铺id获取店铺信息
     * @param $store_id
     * @return mixed
     */
    public function getStoreNameById($store_id)
    {
        return $this->storeRepository->getStoreNameById($store_id);
    }

    /**
     * 关闭店铺 暂时休息
     * @param $store_id
     * @param $operation
     */
    public function closeOpenStore($store_id, $operation)
    {
        $update = [
            'close' => $operation
        ];

        $this->storeRepository->update($update, $store_id);
    }

    //修改店铺信息
    public function updateStore($requestData)
    {
        $store_id = $requestData['store_id'];
        if (array_key_exists('open_time', $requestData)) {
            $this->updateStoreCheckOpenTime($requestData);
        }

        return $this->storeRepository->updateStore($store_id, $requestData);
    }

    //获取店铺支付方式提成
    public function getStorePaymentRoyalty($store_id)
    {
        return $this->storePaymentRoyaltyRepository->findByField(['store_id' => $store_id])->first();
    }

    //修改店铺支付方式提成
    public function updateStorePaymentRoyalty(
        $store_id, $wechat, $alipay, $cash, $bank_card, $group_buy, $member_card
    )
    {
        return $this->storePaymentRoyaltyRepository->updateStorePaymentRoyalty(
            $store_id, $wechat, $alipay, $cash, $bank_card, $group_buy, $member_card
        );
    }

    /**
     * 保存店铺介绍
     * @param $store_id
     * @param $image
     * @param $video
     * @throws ValidatorException
     */
    public function createStoreProfile($store_id, $image, $video)
    {

        DB::beginTransaction();
        try {

            //删除之前的店铺资源
            $this->storeResourceRepository->deleteStoreAllResource($store_id);

            //创建视频资源
            if ($video) {
                $this->storeResourceRepository->createResource($store_id, $video, 2);

            }
            //创建图片资源
            if ($image) {

                $image = explode(',', $image);

                foreach ($image as $key => $value) {
                    $this->storeResourceRepository->createResource($store_id, $value, 1);
                }

            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw new DbException();
        }
    }

    //修改店铺信息时检测开店时间
    private function updateStoreCheckOpenTime($requestData)
    {
        $open_time = $requestData['open_time'];

        if (!array_key_exists('close_time', $requestData)) {
            throw new AllValidatorException(['msg' => '缺少关店时间']);
        } else {
            $close_time = $requestData['close_time'];
        }


        $open_time = explode(":", $open_time);
        $close_time = explode(":", $close_time);

        if (count($open_time) != 2) {

            throw new AllValidatorException(['msg' => '开店时间格式错误']);

        }

        if ($open_time[0] > 24 || $open_time[0] < 0) {

            throw new AllValidatorException(['msg' => '开店时间格式错误']);

        }

        if ($open_time[1] > 60 || $open_time[1] < 0) {

            throw new AllValidatorException(['msg' => '开店时间格式错误']);

        }

        if (count($close_time) != 2) {

            throw new AllValidatorException(['msg' => '开店时间格式错误']);

        }

        if ($close_time[0] > 24 || $close_time[0] < 0) {

            throw new AllValidatorException(['msg' => '开店时间格式错误']);

        }

        if ($close_time[1] > 60 || $close_time[1] < 0) {

            throw new AllValidatorException(['msg' => '开店时间格式错误']);

        }

        if ($open_time[0] > $close_time[0]) {

            throw new AllValidatorException(['msg' => '开店时间格式错误']);

        }

        if ($open_time[0] == $close_time[0] && $close_time[1] <= $open_time[1]) {

            throw new AllValidatorException(['msg' => '开店时间格式错误']);

        }
        return true;
    }

    /**
     * 新增店铺相册
     * @param $store_id
     * @param $image
     * @return mixed
     * @throws
     */
    public function createStorePhoto($store_id, $image)
    {
        DB::beginTransaction();
        try {
            // 创建图片资源
            $image_id = $this->pictureRepository->add("", $image);
            // 更新门店logo
            $id = $this->storePhotoRepository->createStorePhoto($store_id, $image_id);
            DB::commit();
            return $id;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new DbException();
        }
    }

    /**
     * 删除店铺相册
     * @param $store_photo_id
     * @return int
     */
    public function deleteStorePhoto($store_photo_id)
    {
        return $this->storePhotoRepository->deleteStorePhoto($store_photo_id);
    }

    public function getStorePhoto($store_id, $pageSize)
    {
        $data = $this
            ->storePhotoRepository
            ->pushCriteria(new GetStorePhotoCriteria($store_id))
            ->paginate($pageSize, ['*']);

        return Utilities::dealPage($data);


    }

    //判断当前店铺环境图数量
    private function checkStorePicNum($store_id)
    {
        $store_picture_num = $this->storeResourceRepository->findByField('store_id', $store_id)->count();
        if ($store_picture_num >= 3) {
            throw new ValidatorException(new MessageBag(['店铺环境图不能大于3张']));
        }
    }


    //店铺排名
    public function rankStore()
    {
        $date = date('Y-m-d', (time() - 18000));
        // 获取所有店铺的营业额
        // 获取所有的的店铺ids列表和各店铺的人数
        $storeList = $this->storeRepository->storeIdsByCode();
        // 获取店铺的理发订单营业额
        $amountList = $this->orderRepository->getStoreAmount($date);
        // 获取店铺的办卡营业额
        $cardAmountList = $this->memberCardFlowRepository->getStoreCardAmount($date);
        // 获取店铺的销售营业额
        $goodAmountList = $this->goodsOrderRepository->getStoreGoodsAmount($date);
        // 提成总计
        $royaltyList = $this->royaltyRepository->getStoreRoyaltyAmount($date);
        // 计算店铺的基本工资情况
        $baseSalaryList = $this->storeRepository->getUserBaseSalary();
        $rankStoreList = [];
        foreach ($storeList as $v) {
            $rankStoreList[$v['adcode'] . '-' . $v['user_count']][] = [
                'store_id' => $v['id'],
                'adcode' => $v['adcode'],
                'user_count' => $v['user_count'],
                'service_amount' => isset($amountList[$v['id']]['amount']) ? $amountList[$v['id']]['amount'] : 0,
                'card_amount' => isset($cardAmountList[$v['id']]['amount']) ? $cardAmountList[$v['id']]['amount'] : 0,
                'goods_amount' => isset($goodAmountList[$v['id']]['amount']) ? $goodAmountList[$v['id']]['amount'] : 0,
                'total_amount' => (isset($amountList[$v['id']]['amount']) ? $amountList[$v['id']]['amount'] : 0) + (isset($cardAmountList[$v['id']]) ? $cardAmountList[$v['id']]['amount'] : 0) + (isset($goodAmountList[$v['id']]) ? $goodAmountList[$v['id']]['amount'] : 0),
                'order_sum' => (isset($amountList[$v['id']]['count']) ? $amountList[$v['id']]['count'] : 0) + (isset($cardAmountList[$v['id']]['count']) ? $cardAmountList[$v['id']]['count'] : 0) + (isset($goodAmountList[$v['id']]['count']) ? $goodAmountList[$v['id']]['count'] : 0),
                'profit_sum' => ((isset($amountList[$v['id']]['count']) ? $amountList[$v['id']]['amount'] : 0) + (isset($cardAmountList[$v['id']]) ? $cardAmountList[$v['id']]['amount'] : 0) + (isset($goodAmountList[$v['id']]['count']) ? $goodAmountList[$v['id']]['amount'] : 0)) - ((isset($storeList[$v['id']]['expenditure']) ? $storeList[$v['id']]['expenditure'] : 0) + (isset($goodAmountList[$v['id']]['buying_sum']) ? $goodAmountList[$v['id']]['buying_sum'] : 0) + (isset($royaltyList[$v['id']]['amount']) ? $royaltyList[$v['id']]['amount'] : 0) + (isset($baseSalaryList[$v['id']]['salary_sum']) ? $baseSalaryList[$v['id']]['salary_sum'] : 0))
            ];
        }
        $rankStoreList = array_map(function ($v) {
            $sortKeys = array_column($v, 'total_amount');
            array_multisort($sortKeys, SORT_DESC, $v);
            return $v;
        }, $rankStoreList);
        $newList = [];

        foreach ($rankStoreList as $item) {
            foreach ($item as $k => $v) {
                $newList[] = [
                    'store_id' => $v['store_id'],
                    'adcode' => $v['adcode'],
                    'rank_date' => time() - 72000,
                    'level' => $k + 1,
                    'value' => $v['total_amount'],
                    'compare_count' => $v['user_count'],
                    'order_sum' => $v['order_sum'],
                    'profit_sum' => $v['profit_sum']
                ];
            }
        }
        return empty($newList) ? false : $this->storeRankRepository->addRankList($newList);
        // 获取同级别的店铺
        // 进行排序
//        return $this->storeRepository->rankStore();
    }


    //查询具体店铺排名
    public function getStoreRank($requestData)
    {
        return $this->storeRankRepository->getStoreRank($requestData);
    }

    /**
     * 小程序获取全部店铺列表
     * @param $user_lng
     * @param $user_lat
     * @param $adcode
     * @param $orderBy
     * @param $keywords
     * @param $pageSize
     * @return array|mixed
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getStoreList($user_lng, $user_lat, $adcode, $orderBy, $keywords, $pageSize)
    {
        $store_list = $this->storeRepository->pushCriteria(new GetStoreListCriteria($user_lng, $user_lat, $adcode, $orderBy, $keywords))->paginate($pageSize, ['*'], 'paginate');
        $store_list = Utilities::dealPage($store_list);

//    	$store_list['data'] = array_map(function($v){
//    		return $v = [
//    			'id'=>$v['id'],
//			    'name'=>$v['name'],
//			    'image'=>$v['image'],
//			    'distance' =>$v['distance'],
//			    'score' => $v['score'],
//			    'price' => $v['price'],
//			    'waiting_time' => $v['waiting_time'],
//			    'store_picture' =>array_filter(array_map(function($k){
//			    	return $k['image'];
//			    },$v['store_picture']),function($s){return !empty($s);})
//		    ];
//	    },$store_list['data']);
        return $store_list;
    }

    /**
     * 小程序获取店铺首页信息
     * @param $store_id
     * @return mixed
     * @throws AllValidatorException
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     * @author Happy dong
     * @modifiedTime 2019-09-09 15:38
     */
    public function getStoreInfo($store_id)
    {
        $info = $this->storeRepository->pushCriteria(new GetStoreInfoCriteria($store_id))->first();
        if (empty($info)) {
            throw new AllValidatorException(['msg' => '店铺不存在', 'statusCode' => 400, 'errorCode' => 1404]);
        } else {
            $info->level = Utilities::getStoreLevel($info->order_sum);
        }
        return $info;
    }

    //小程序用户关注店铺
    public function likeStore($member_id, $store_id, $operation)
    {
        if ($operation == 1) {//关注
            return $this->storeLikeRepository->likeStore($member_id, $store_id);
        } else {//取消关注
            return $this->storeLikeRepository->unLikeStore($member_id, $store_id);
        }
    }

    /*
     * 小程序用户获取本人关注的店铺列表
     */
    public function getMyLikeStoreList($member_id, $pageSize)
    {

        $list = $this->storeRepository->pushCriteria(new GetMyLikeStoreCriteria($member_id))->paginate($pageSize, ['*']);

        $list = Utilities::dealPage($list);

        return $list;
    }

    /**
     * 获取店铺信息列表
     * @param $storeIds
     * @return mixed
     */
    public function getStoreInfoListByIds($storeIds)
    {
        return $this->storeRepository->getStoreInfoList($storeIds);
    }

    /**
     * 获取店铺信息
     * @param $storeId
     * @return mixed
     */
    public function getStoreInfoById($storeId)
    {
        return $this->storeRepository->getStoreInfoById($storeId);
    }

    /**
     * 获取店铺收款码
     * @param $store_id
     */
    public function getStorePaymentCode($store_id)
    {
        return $this->storeRepository->pushCriteria(new GetStorePaymentCodeCriteria($store_id))->first();
    }

    /** 获得店铺介绍
     * @param $store_id
     * @return array
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getStoreProfile($store_id)
    {
        return [
            'video' => $this->storeResourceRepository->pushCriteria(new GetStoreViedoCriteria($store_id))->first(),
            'images' => $this->storeResourceRepository->resetCriteria()->pushCriteria(new GetStorePictureCriteria($store_id))->get()
        ];
    }

    /**
     * 设置用户角色
     * @param $userId
     * @param $storeId
     * @param $role
     * @return array|int
     * @throws \App\Exceptions\NotFoundException
     */
    public function setUserStoreRole($userId, $storeId, $role)
    {
        $this->employeeRepository->isExited($userId);
        $storeInfo = $this->storeRepository->isExited($storeId);
        $userIds = $storeInfo->user_id;
        $role = empty($role) ? [] : array_filter(explode(',', $role));
        if ($userIds == $userId) {
            if (!in_array(config('constant.role.manager'), $role)) {
                array_push($role, config('constant.role.manager'));
                array_push($role, config('constant.role.barber'));
            }
        }
        // 店长权限默认有理发师权限
        if (in_array(config('constant.role.manager'), $role)) {
            if (!in_array(config('constant.role.barber'), $role)) {
                array_push($role, config('constant.role.barber'));
            }
        }
        return empty($role) ?
            $this->userStoreRepository->delRole($userId, $storeId)
            :
            $this->userStoreRepository->setRole($userId, $storeId, $role);
    }

    public function getStoreRankInfo($storeId)
    {
        return $this->storeRepository->findStoreRankByStoreId($storeId);
//		$info = $this->storeRankRepository->findByStoreId($storeId);
//
//		if(isset($info)){
//			$info->store->logo = empty($info->store) ? null: empty($info->store->picture) ? null : $info->store->picture->image;
//			if(!empty($info->store->logo))  unset($info->store->picture);
//		}
//		return $info;
    }


    /**
     * 获取角色的基本工资
     * @param $storeId
     * @param $userId
     * @param $role
     * @return mixed
     */
    public function getBaseSalaryByUserId($storeId, $userId, $role)
    {
        return $this->userStoreRepository->getBaseSalary($storeId, $userId, $role);
    }


    /**
     * 判断是否上线
     * @param $store_id
     * @return array
     */
    public function checkIsOnline($store_id)
    {
        //判断有无logo
        $store = $this->storeRepository->getStoreNameById($store_id);
        $logo = $store->logo ? 1 : 0;

        //判断店铺简介图视频是否满四张
        $store_resource_count = $this->storeResourceRepository->getStoreResourceCount($store_id);

        $store_resource = $store_resource_count == 3 ? 1 : 0;

        //判断店铺是否发布服务
        $store_service_count = $this->serviceRepository->getStoreServiceArray($store_id);

        $store_service = $store_service_count ? 1 : 0;

        return [
            [
                'id' => 1,
                'name' => '是否上传logo',
                'is_satisfy' => $logo
            ],
            [
                'id' => 2,
                'name' => '是否上传店铺简介',
                'is_satisfy' => $store_resource
            ],
            [
                'id' => 3,
                'name' => '是否发布服务',
                'is_satisfy' => $store_service
            ],
        ];
    }

    /**
     * 注销店铺
     * @param $store_id
     * @return bool
     * @throws AllValidatorException
     * @throws DbException
     */
    public function cancellationStore($store_id)
    {
        $user_id = FLAuth::id();
        //判断是否是店长
        $store = $this->storeRepository->find($store_id);
        if ($store->user_id != $user_id) {
            throw new AllValidatorException(['msg' => '您不是老板 不可以注销店铺']);
        }
        //判断有无理发师
        $barber_num = count($this->userStoreRepository->getUserListByStoreId($store_id));

        if ($barber_num > 1) {
            throw new AllValidatorException(['msg' => '该店铺还有其他理发师 暂不可删除']);
        }

        //判断有无正在进行的订单
        $order_num = $this->orderRepository->getUnderwayOrderNum($store_id);
        if ($order_num > 0) {
            throw new AllValidatorException(['msg' => '该店铺还有正在进行中的订单 暂不可删除']);
        }

        DB::beginTransaction();

        try {
            $this->storeRepository->delete($store_id);
            $this->userStoreRepository->deleteWhere(['uid' => $user_id, 'sid' => $store_id]);
            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new DbException();
        }


    }

    /**
     * OSS方式更新店铺LOGO
     * @param $store_id
     * @param $oss_url
     * @throws
     */
    public function updateStoreLogo($store_id, $oss_url)
    {
        DB::beginTransaction();
        try {
            // 创建图片资源
            $image_id = $this->pictureRepository->add("", $oss_url);
            // 更新门店logo
            $this->storeRepository->updateLogo($store_id, $image_id);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new DbException();
        }
    }

	/**
	 * 直播间数
	 * @return mixed
	 */
    public function getLiveRoomNums(){
    	return $this->liveRepository->findWhere(['status'=>1])->count();
    }


}
